<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view
    id="input-height"
    class="Mall4j page-chat chat-container"
    :class="{ chatad: modelType }"
    :style="{ position: modelType || fixedFlag ? 'static' : 'fixed' }"
  >
    <view class="content">
      <!-- #ifdef H5 -->
      <view
        class="shop-info"
        @touchmove.stop.prevent="discard"
      >
        <image
          class="back-icon"
          src="../../static/images/chat/down-arrow.png"
          @tap="backToPre"
        />
        <view
          class="shop-tit"
        >
          {{ userName || '消息盒子' }}
        </view>
      </view>
      <!-- #endif -->
      <scroll-view
        id="input-text"
        class="msg-list"
        scroll-y
        :style="{ height: screenHeight + 'px' }"
        :scroll-with-animation="scrollAnimation"
        :scroll-top="chatScrollTop"
        @scrolltoupper="changeScollY"
        @scroll="bindscroll"
        @touchstart="hideKeyboard"
        @touchmove="touchMove"
        @touchend="touchEnd"
      >
        <view
          v-if="showRefresh"
          style="width: 100%; position: relative; padding: 60rpx 0"
        >
          <view
            class="text-gray"
            style="
              position: absolute;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
            "
          >
            <view class="flex">
              <view class="lzy-loading" />
            </view>
          </view>
        </view>
        <view
          v-for="(m, index) in messages"
          id="index"
          :key="index"
          class="row"
          @touchmove="touchMove"
        >
          <view
            v-if="m.timeStr"
            class="topTime"
          >
            {{ m.timeStr }}
          </view>
          <!-- 自己发出的消息 -->
          <view
            v-if="m.send||m.content.text.sender"
            class="my-name"
          >
            <view class="txt">
              {{ getChannelInfo(m,'nickName') }}
            </view>
          </view>
          <view
            v-if="m.send||m.content.text.sender"
            class="my"
          >
            <!-- 左-消息 -->
            <view class="left">
              <!-- 文字消息 -->
              <view
                v-if="maxReadSeq>=m.messageSeq"
                class="unread"
              >
                已读
              </view>
              <view
                v-else
                class="unread"
              >
                未读
              </view>

              <!-- 文字消息 -->
              <view
                v-if="(m.content.text?.msgType===-1||m.content.text?.msgType===1||m.content.text?.type===-5)&&m.content.text?.type!==-1"

                class="bubble"
              >
                <text> {{ m.content.text.msg }} </text>
              </view>
              <view
                v-if="m.content.text?.type===-1"
                class="bubble"
                style="display: block;"
              >
                <view
                  v-if="m.content.text.sendTextState"
                >
                  {{ m.content.text.content }}
                </view>

                <view
                  v-if="m.content.text.sendIssusState"
                >
                  <view
                    v-for="item in m.content.text.issues"
                    :key="item.id"
                    class="issues"
                  >
                    • {{ item.issues }}
                  </view>
                </view>
              </view>
              <!-- 图片消息 -->
              <view
                v-if="m.content.text?.msgType===2"
                class="bubble"
                @tap="showPic(util.checkFileUrl(m.content.text.msg))"
              >
                <image
                  :src="util.checkFileUrl(m.content.text.msg)"
                  class="longimage"
                  mode="widthFix"
                  @load="picLoad"
                />
              </view>
            </view>
            <!-- 右-头像 -->
            <view class="right">
              <img-show
                :src="channelInfo?.logo || ''"
                :def-img-inx="2"
              />
            </view>
          </view>

          <!-- 别人发出的消息 -->
          <view
            v-if="m.send===false&&m.content.text?.type!==-5&&!m.content.text.sender"
            class="other"
          >
            <!-- 左-头像 -->
            <view class="left">
              <img-show
                :src="getChannelInfo(m,'pic')"
                :def-img-inx="2"
              />
            </view>
            <!-- 右-用户名称-时间-消息 -->
            <view
              class="right"
            >
              <view
                v-if="m.content.text?.msgType===1"
                class="bubble"
              >
                <rich-text :nodes="m.content.text.msg" />
              </view>
              <!-- 图片消息 -->
              <view
                v-if="m.content.text?.msgType===2"
                class="bubble"
                @tap="showPic(util.checkFileUrl(m.content.text.msg))"
              >
                <image
                  :src="util.checkFileUrl(m.content.text.msg)"
                  class="longimage"
                  mode="widthFix"
                  @load="picLoad"
                />
              </view>
              <!-- 商品链接 -->
              <view
                v-if="m.content.text?.msgType===4"
                class="prod-link"
                @tap=" toProdDetail(m.content.text.msg,m.content.text.msg.orderFlag ? 1 : 0)"
              >
                <view
                  v-if="m.content.text.msg.orderFlag"
                  class="prod-number"
                >
                  订单编号：{{ m.content.text.msg.orderNumber }}
                </view>
                <view class="link-prod prod-no">
                  <img
                    :src="util.checkFileUrl(m.content.text.msg.imgs)"
                    alt=""
                    @error="errImg(index)"
                  >
                  <view class="link-detail">
                    <view class="prod-name">
                      {{ m.content.text.msg.prodName }}
                    </view>
                    <view class="prod-price">
                      <!-- <text v-if="row.prodInfo.orderFlag">{{$t('paymentAmount')+':'}}{{ row.prodInfo.actualTotal?'￥'+row.prodInfo.actualTotal: ' ' }}<text v-if="row.prodInfo.useScore">{{row.prodInfo.actualTotal?'+':''}}{{row.prodInfo.useScore}} {{$t('points')}}</text></text> -->
                      <text>
                        {{ m.content.text.msg.actualTotal ? '￥' : '' }}
                        {{ m.content.text.msg.actualTotal ? m.content.text.msg.actualTotal : '' }}
                        {{ (m.content.text.msg.actualTotal && m.content.text.msg.useScore) ? '+' : '' }}
                        <text v-if="m.content.text.msg.useScore">
                          {{ m.content.text.msg.useScore }} {{ $t('prodDetail.points') }}
                        </text>
                      </text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 底部输入栏 -->
    <!-- :style="{bottom:chatFocus?1:calc(env(safe-area-inset-bottom)/2)}" -->
    <view
      :class="['input-box', footPd ? 'input-box-pad' : '']"
      @touchmove.stop.prevent="discard"
    >
      <view class="textbox">
        <view
          class="text-mode"
          @tap="chatFocus"
        >
          <view class="box">
            <input
              v-model="textMsg"
              type="text"
              confirm-type="send"
              style="width: 100%"
              @confirm="sendText(1)"
              @blur="listeningfocus"
            >
          </view>
        </view>
      </view>
      <view
        class="more"
        @tap="showMore"
      >
        <image
          class="icon add"
          src="../../static/images/chat/add.png"
        />
      </view>
      <view
        class="send"
        @tap="sendText(1)"
      >
        <view class="btn">
          发送
        </view>
      </view>
    </view>

    <!-- 抽屉栏 -->
    <view
      class="popup-layer"
      @touchmove.stop.prevent="discard"
    >
      <!-- 更多功能 相册-拍照-红包 -->
      <view
        class="more-layer"
        :class="{ hidden: hideMore }"
      >
        <view class="list">
          <view
            class="box"
            @tap="chooseImage"
          >
            <view class="icon tupian2" />
          </view>
          <view
            class="box"
            @tap="camera"
          >
            <view class="icon paizhao" />
          </view>
        </view>
      </view>
    </view>

    <!-- 未读消息提醒-->
    <!-- <view class="un-read-tips" v-if="totalUserUnread>0">
        <image src="../../../static/images/icon/unread-up.png" class="un-read-icon"/>
        {{`${totalUserUnread}${$t('newMessage')}`}}
      </view> -->
    <helang-compress ref="hCompressRef" />
  </view>
</template>

<script setup>
import util from '@/utils/util'
import { ConnectStatus, WKSDK, ChannelTypeGroup, Channel, MessageText, PullMode, ConversationAction } from 'wukongimjssdk'
import { Convert } from '@/utils/convert'
// 文字消息
const textMsg = ref('')
const scrollAnimation = ref(false)
let current = 1 // 聊天记录页数
const pages = ''// 聊天记录页码数
// 抽屉参数
// more参数
const hideMore = ref(true)
const msgItems = ref([])
const shopInfo = ref(null)
const loginOtherSide = false // 判断用户是否在别处登录
const chatScrollTop = ref(0)
const screenHeight = ref(712) // 消息内容盒子默认高度
const softKeyboards = false
let oldScreenHeight = null
const screenOnce = 0
const modelType = ref(null)
const footPd = ref(null)
const fixedFlag = ref(null)

let freshStatus = 'more' // 当前刷新的状态
const showRefresh = ref(false) // 是否显示下拉刷新组件
let scollTopTag = ''
let startY = ''

let currentUserId = ''
const userName = ref('')
let sensitiveWords = ''// 敏感词

const userStore = useUserStore()
const shopId = computed(() => userStore.shopId)
let isDestroy = 0
onLoad((option) => {
  nextTick(getSysInfo)
  getShopInfo()
  getSensitiveWords()
  currentUserId = option.userId
  userName.value = option.userName
  isDestroy = +option.isDestroy
  uni.setNavigationBarTitle({
    title: '消息盒子'
  })
  getWuKongIm()
  WKSDK.shared().chatManager.addCMDListener(cmdListener) // 监听cmd消息
})
onUnload(() => {
  WKSDK.shared().chatManager.removeMessageListener(messageListener)

  WKSDK.shared().disconnect()
  WKSDK.shared().chatManager.removeCMDListener(cmdListener)

  // console.log('onUnload-im')
})
// 下拉加载刷新页面
onPullDownRefresh(() => {
  current += 1
  if (loginOtherSide) {
    wx.stopPullDownRefresh()
    // wx.showToast({
    //   title: $t('loginOtherSide'),
    //   icon: 'none',
    // })
  } else if (current <= pages) {
    getMsgItems()
  } else {
    wx.stopPullDownRefresh()
    // wx.showToast({
    //   title: $t('allLoaded'),
    //   icon: 'none',
    // })
  }
})

// 兼容小程序
// ...mapState(["baseUrl"])
const changeScollY = () => {
  scollTopTag = 0
}
/**
 * 获取屏幕高度
 */
const getSysInfo = () => {
  uni.getSystemInfo({
    success: (sysInfo) => {
      // #ifdef H5
      // screenHeight = sysInfo.windowHeight - 55
      if (sysInfo.platform === 'ios') {
        modelType.value = true
      } else {
        /* #ifndef H5 */
        footPd.value = true
        /* #endif */
      }
      if (softKeyboards) {
        // let kebodyHeight = screen.height - window.innerHeight
        screenHeight.value = oldScreenHeight
      } else {
        screenHeight.value = sysInfo.windowHeight - 55
        if (!screenOnce) {
          oldScreenHeight = screenHeight.value
        }
      }
      // #endif
      // #ifdef MP-WEIXIN
      screenHeight.value =
        sysInfo.screenHeight - 105 - sysInfo.statusBarHeight
      oldScreenHeight = screenHeight.value
      uni.showToast({
        title: oldScreenHeight
      })
      // #endif
      // #ifdef APP-PLUS
      screenHeight.value = sysInfo.windowHeight - 50

      oldScreenHeight = screenHeight.value
      // #endif
    }
  })
}

/**
 * 点击外面盒子获取焦点
 */
const chatFocus = () => {
  textareaFocus()
}

/**
 * 打电话给商家
 */
// const callShop = () => {
//   uni.makePhoneCall({
//     phoneNumber: shopInfo.value.tel
//   })
// }
/**
 * 返回上一页
 */
const prodId = ''
const backToPre = () => {
  const canNavBack = getCurrentPages()
  if (prodId) {
    uni.navigateTo({ url: '/pages/prod/prod?prodid=' + prodId })
  } else {
    if (shopId.value == 0) {
      if (canNavBack && canNavBack.length > 1) {
        uni.navigateBack({
          delta: 1
        })
      } else {
        history.back()
      }
    } else {
      uni.navigateBack({
        url: '/package-user/pages/chat/chat'
      })
    }
  }
}
/**
 * 获取店铺信息
 */
const getShopInfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET',
    data: {
      shopId: shopId.value
    }
  }
  http.request(params).then(({ data: res }) => {
    shopInfo.value = res
  })
}

// 判断是否为JSON格式
const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}

/**
 * 获取聊天记录
 */
const getMsgItems = async () => {
  if (messages.value.length == 0) {
    return
  }
  const firstMsg = messages.value[0]
  if (messages.value[0].messageSeq == 1 || !messages.value[0].messageSeq) {
    return
  }
  const limit = 10
  const msgs = await WKSDK.shared().chatManager.syncMessages(to.value, {
    limit,
    startMessageSeq: firstMsg.messageSeq - 1,
    endMessageSeq: 0,
    pullMode: PullMode.Down
  })
  if (msgs[msgs.length - 1].content.text.prodInfo) {
    msgs.pop()
  }
  if (msgs && msgs.length > 0) {
    msgs.reverse().forEach((m) => {
      messages.value.unshift(m)
    })
  }
  uni.stopPullDownRefresh()
  showRefresh.value = false
  nextTick(() => {
    chatScrollTop.value = 0
  })
}

/**
 * 发送信息
 */
const sendText = () => {
  if (shopInfo.value.shopStatus !== 1 || shopStatus) {
    uni.showToast({
      title: '商家已下线,请恢复上线',
      icon: 'none'
    })
    return
  }
  if (isDestroy || isDestroyArr.includes(to.value.channelID)) {
    uni.showToast({
      title: '账户已注销',
      icon: 'none'
    })
    textMsg.value = ''
    return
  }
  if (!noAccountable) {
    textMsg.value = ''
    uni.showToast({
      title: '不是你负责的客户',
      icon: 'none'
    })
    return
  }
  // type 1 = 发送消息  type 2 = 发送商品链接

  // source 0 是平台  1 是商家  2 是顾客

  // if (type === 1) {
  if (textMsg.value === '' || !currentUserId || textMsg.value.match(/^\s+$/)) {
    uni.showToast({
      title: '不能发送空白消息哦',
      icon: 'none'
    })
    return
  }
  // }
  if (sensitiveWords) {
    try {
      const rep = new RegExp(sensitiveWords, 'g')
      textMsg.value = textMsg.value.replaceAll(rep, '**')
    } catch (e) {
      // console.log(e)
    }
  }
  let content = ''
  const msgObj = JSON.stringify({ msg: textMsg.value, msgType: 1, sender: -1 })
  content = new MessageText(msgObj)
  WKSDK.shared().chatManager.send(content, to.value)
  textMsg.value = ''
}
/**
 * @param {Object} _messageInfo
 * 将新发送的消息添加至页面
 */

/**
 * 更多功能(点击+弹出)
 */
const showMore = () => {
  if (hideMore.value) {
    openDrawer()
  } else {
    hideDrawer()
  }
}
/**
 * 打开抽屉
 */
const openDrawer = () => {
  hideMore.value = false
  nextTick(() => {
    screenHeight.value = oldScreenHeight - 90
    chatScrollTop.value += 1
  })
}
/**
 * 隐藏抽屉
 */
const hideDrawer = (wxNeedSub, noSliding) => {
  // #ifdef H5
  nextTick(() => {
    screenHeight.value = oldScreenHeight
  })
  // #endif

  // #ifdef MP-WEIXIN || APP-PLUS
  nextTick(() => {
    if (wxNeedSub) {
      screenHeight.value = oldScreenHeight - 90
    } else {
      screenHeight.value = oldScreenHeight
    }
  })
  // #endif
  hideMore.value = true

  //  防止滑动时页面触底
  if (!noSliding) {
    nextTick(() => {
      chatScrollTop.value += 1
    })
  }
}
/**
 * 获取焦点，如果不是选表情ing,则关闭抽屉
 */
const textareaFocus = () => {
  // #ifdef H5
  fixedFlag.value = true
  // #endif

  hideDrawer(!hideMore.value)
}

// 失去焦点软键盘变回原样
// :style="{position:fixedFlag?'static':'fixed'}"
const listeningfocus = () => {
  fixedFlag.value = null
  hideDrawer(false)
}
/**
 * 选择图片发送
 */
const chooseImage = () => {
  getImage('album')
}
/**
 * 拍照发送
 */
const camera = () => {
  getImage('camera')
}

// 触摸开始
const hideKeyboard = (e) => {
  uni.hideKeyboard()
  hideDrawer(false, true)
  startY = e.changedTouches[0].pageY
  freshStatus = 'more'
}
// 触摸结束
const touchEnd = () => {
  if (freshStatus == 'end') {
    // 延迟 500 毫秒，显示 “刷新中”，防止请求速度过快不显示
    current += 1
    if (loginOtherSide) {
      uni.stopPullDownRefresh()
      uni.showToast({
        title: '用户在别处登陆,请刷新页面',
        icon: 'none'
      })
      showRefresh.value = false
    } else if (moreMsg != 0) {
      freshStatus = 'fresh'
      getMsgItems()
    } else {
      uni.stopPullDownRefresh()
      uni.showToast({
        title: '已全部加载完毕',
        icon: 'none'
      })
      showRefresh.value = false
    }
  } else {
    showRefresh.value = false
  }
}
// 滚轮移动
const bindscroll = (e) => {
  nextTick(() => {
    scollTopTag = e.detail.scrollTop
  })
}
// 触摸移动
const touchMove = (e) => {
  if (scollTopTag !== 0) {
    const query = uni.createSelectorQuery()
    query.select('#input-text').scrollOffset()
    query.exec((res) => {
      scollTopTag = res[0].scrollTop
    })
  }
  if (scollTopTag > 0) {
    return
  }
  e.preventDefault()
  const endY = e.changedTouches[0].pageY
  const dis = endY - startY
  // 判断是否下拉
  if (dis <= 0) {
    return
  }
  if (dis > 20) {
    showRefresh.value = true
    // freshStatus = 'end'
    if (dis > 50) {
      freshStatus = 'end'
    } else {
      freshStatus = 'more'
    }
  } else {
    showRefresh.value = false
  }
}
/**
 * @param {Object} type
 * 选照片 or 拍照
 */
const hCompressRef = ref(null)
const getImage = (type) => {
  if (shopInfo.value.shopStatus !== 1 || shopStatus) {
    uni.showToast({
      title: '商家已下线,请恢复上线',
      icon: 'none'
    })
    return
  }
  if (isDestroy || isDestroyArr.includes(to.value.channelID)) {
    uni.showToast({
      title: '账户已注销',
      icon: 'none'
    })
    textMsg.value = ''
    return
  }
  if (!noAccountable) {
    textMsg.value = ''
    uni.showToast({
      title: '不是你负责的客户',
      icon: 'none'
    })
    return
  }
  hideDrawer()
  util.chooseImage({ compress: hCompressRef.value?.compress, sourceType: [type], sizeType: ['original', 'compressed'], count: 9 }).then(data => {
    data.forEach((item) => {
      const msgObj = JSON.stringify({ msg: item.filePath, msgType: 2 })
      const content = new MessageText(msgObj)
      WKSDK.shared().chatManager.send(content, to.value)
    })
  })
}

/**
 * @param {Object} msg
 * 预览图片
 */
const showPic = (msg) => {
  const list = []
  list.push(util.checkFileUrl(msg))
  uni.previewImage({
    indicator: 'none',
    current: 0,
    urls: list
  })
}
/**
 * 用于阻止滚动的空方法
 */
const discard = () => {}

// 图片加载失败
const errImg = (index) => {
  const obj = msgItems.value[index]
  obj.prodInfo.imgs = '/static/images/def.png'
  msgItems.value[index] = obj
}

/**
 * 链接点击去往商品详情
 */
const toProdDetail = (prodInfo, type) => {
  if (type === 0) {
    uni.navigateTo({
      url: `/package-prod/pages/prod-management/prod-management?prodId=${prodInfo.prodId}`
    })
  } else {
    uni.navigateTo({
      url: `/package-order/pages/order-detail/order-detail?orderNumber=${prodInfo.orderNumber}`
    })
  }
}
// 敏感词
const getSensitiveWords = () => {
  const params = {
    url: '/sys/webConfig/info/SENSITIVE_WORDS',
    method: 'GET'
  }
  http.request(params).then(({ data }) => {
    // console.log(data)
    data = JSON.parse(data)
    if (data?.sensitiveWord) {
      sensitiveWords = data.sensitiveWord.replaceAll('，', '|')
    }
  })
}
// 图片加载完成
const picLoad = (e) => {
  const height = e.detail.height
  if (freshStatus === 'more') {
    chatScrollTop.value = chatScrollTop.value + height + 100
  }
}
let connectStatusListener
let messageListener
const getWuKongIm = () => {
  const params = {
    url: '/shop/wuKongIm/registerOrLogin?token=' + uni.getStorageSync('bbcToken_us'),
    method: 'POST'
  }
  http.request(params).then(({ data }) => {
    getShopChannelInfo()

    const config = WKSDK.shared().config
    config.addr = import.meta.env.VITE_APP_WS_IM_API
    config.uid = data.uid // 用户uid（需要在悟空通讯端注册过）
    config.token = data.token// 用户token （需要在悟空通讯端注册过）
    config.debug = true
    config.deviceFlag = 1
    WKSDK.shared().config = config
    WKSDK.shared().connect()
    // 监听连接状态
    connectStatusListener = (status) => {
      if (status === ConnectStatus.Connected) {
        console.log('连接成功')
      } else {
        console.log('连接断开')
      }
    }
  })
  WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener)
  messageListener = (msg) => {
    if (isJSON(msg.content.text)) {
      msg.content.text = JSON.parse(msg.content.text)
    }
    const type = msg.content.text.type
    if (msg.send && type !== -1 && msg.content.text.msgType !== -1 && updateAuto) {
      http.request({ url: '/shop/wuKongIm/updateAuto?channelId=' + msg.channel.channelID, method: 'POST' })
      updateAuto = false
    }

    msg.messageSeq = ++lastMessageSeq // 新发送的消息没有序列号,此处添加序列号
    http.request({ url: '/shop/wuKongIm/conversations/setUnread', data: { channel_id: to.value.channelID, maxSeq: lastMessageSeq }, method: 'POST' })
    if (to.value.channelID === msg.channel.channelID) {
      if (msg.content.text.sender === 1) {
        http.request({ url: '/shop/wuKongIm/getShopChannelInfo?userId=' + currentUserId, method: 'POST' }).then(({ data }) => {
          noAccountable = !!data.isWhiteUser
        })
      }
      if (messages.value.length) {
        const prevTime = util.tsToDate(
          messages.value[messages.value.length - 1].timestamp * 1000,
          'M月D日 h:m'
        )
        const nowTime = util.tsToDate(new Date().getTime(), 'M月D日 h:m')
        if (prevTime.slice(0, prevTime.indexOf(' ')) === nowTime.slice(0, nowTime.indexOf(' '))) {
          msg.timeStr = util.tsToDate(new Date().getTime(), 'h:m')
        } else {
          msg.timeStr = util.tsToDate(new Date().getTime(), 'M月D日 h:m')
        }
        const timeFlag = util.timeBeApart(messages.value[messages.value.length - 1].timestamp * 1000, new Date().getTime())
        if (timeFlag) {
          delete msg.timeStr
        }
      } else {
        msg.timeStr = util.tsToDate(new Date().getTime(), 'M月D日 h:m')
      }
      if (!to.value.isEqual(msg.channel)) {
        return
      }
      messages.value.push(msg)
      nextTick(() => {
        chatScrollTop.value = chatScrollTop.value + 1000 * messages.value.length
      })
    }
  }
  WKSDK.shared().chatManager.addMessageListener(messageListener)
}

const maxReadSeq = ref(0)
const to = ref(new Channel('', ChannelTypeGroup))
let updateAuto = false
let noAccountable = false
const getShopChannelInfo = () => {
  const params = {
    url: '/shop/wuKongIm/getShopChannelInfo?userId=' + currentUserId,
    method: 'POST'
  }
  http.request(params).then(({ data }) => {
    if (data) {
      noAccountable = !!data.isWhiteUser
      if (data.imChannel.sendAutoReply === 1) {
        updateAuto = isDateBeforeToday(data.imChannel.personReplyTime)
      }
      http.request({ url: '/shop/wuKongIm/conversations/setUnread', method: 'POST', data: { channel_id: data.imChannel.channelId, maxSeq: data.imChannel.userReadSeq } })
      maxReadSeq.value = data.imChannel.userReadSeq
      to.value.channelID = data.imChannel.channelId
      clearConversationUnread(to.value)
      pullLast()
    }
  })
}
const isDateBeforeToday = (dateTimeString) => {
  if (!dateTimeString) {
    return true
  }
  // 将日期时间字符串转换为日期对象
  const givenDate = new Date(dateTimeString)
  // 获取当前日期的年、月、日
  const today = new Date()
  const todayYear = today.getFullYear()
  const todayMonth = today.getMonth()
  const todayDay = today.getDate()
  givenDate.setHours(0, 0, 0, 0)
  return (
    givenDate.getFullYear() < todayYear ||
    (givenDate.getMonth() < todayMonth && givenDate.getFullYear() === todayYear) ||
    (givenDate.getDate() < todayDay &&
      givenDate.getMonth() === todayMonth &&
      givenDate.getFullYear() === todayYear)
  )
}
// 获取某个频道的最近会话
const clearConversationUnread = (channel) => {
  const conversation = WKSDK.shared().conversationManager.findConversation(channel)
  if (conversation) {
    conversation.unread = 0
    WKSDK.shared().conversationManager.notifyConversationListeners(conversation, ConversationAction.update)
  }
}
let lastMessageSeq = 0
const messages = ref([])
const pullLast = async () => {
  const msgs = await WKSDK.shared().chatManager.syncMessages(to.value, {
    limit: 15,
    startMessageSeq: 0,
    endMessageSeq: 0,
    pullMode: PullMode.Up
  })
  lastMessageSeq = msgs[msgs.length - 1]?.messageSeq || msgs[msgs.length - 2]?.messageSeq || 0// 最后一条消息可能是商品链接即取倒数第二条
  if (msgs && msgs.length > 0) {
    msgs.forEach((m) => {
      messages.value.push(m)
      fetchChannelInfoIfNeed(m.channel)
    })
  }
  setTimeout(() => {
    nextTick(() => {
      chatScrollTop.value = chatScrollTop.value + 1200 * messages.value.length
    })
  }, 100)
}
// 同步自己业务端的频道消息列表
// 同步自己业务端的频道消息列表
let moreMsg = 0
WKSDK.shared().config.provider.syncMessagesCallback = async (channel, opts) => {
  const resultMessages = []
  const limit = 10
  const params = {
    url: '/shop/wuKongIm/channel/messageSync',
    method: 'POST',
    data: {
      channel_id: channel.channelID,
      channel_type: channel.channelType,
      start_message_seq: opts.startMessageSeq,
      end_message_seq: opts.endMessageSeq,
      pull_mode: opts.pullMode,
      limit
    }
  }
  const { data } = await http.request(params)
  moreMsg = data.more
  const messageList = data && data.messages
  if (messageList) {
    messageList.forEach((msg) => {
      const message = Convert.toMessage(msg)
      message.content.text = JSON.parse(message.content.text)
      message.timeStr = util.tsToDate(
        message.timestamp * 1000,
        'M月D日 h:m'
      )
      resultMessages.push(message)
    })

    resultMessages.length > 0 && resultMessages.reduce((prev, cur) => {
      // 将时间更换为某某月某某日 要是是当天即去掉月日
      const now = util.tsToDate(prev.timestamp * 1000, 'M月D日 h:m')
      const next = util.tsToDate(cur.timestamp * 1000, 'M月D日 h:m')
      if (
        now.slice(0, now.indexOf(' ')) ===
            next.slice(0, next.indexOf(' '))
      ) {
        cur.timeStr = util.tsToDate(cur.timestamp * 1000, 'h:m')
      }

      // 历史记录进行时间段显示判断
      if (resultMessages.length > 2) {
        const timeFlag = util.timeBeApart(prev.timestamp * 1000, cur.timestamp * 1000)
        if (timeFlag) {
          delete cur.timeStr
        }
      }
      return cur
    })
  }

  return resultMessages
}
const channelInfo = ref()

const fetchChannelInfoIfNeed = async (channel) => {
  if (channel) {
    channelInfo.value = WKSDK.shared().channelManager.getChannelInfo(channel)// 获取频道详情(不会触发数据源的远程获取)
    if (!channelInfo.value) {
      await WKSDK.shared().channelManager.fetchChannelInfo(channel)
    }
  }
}
WKSDK.shared().config.provider.channelInfoCallback = async (channel) => {
  const { data } = await http.request({ url: '/shop/wuKongIm/listChannelSubcribers?channelId=' + channel.channelID, method: 'GET' })
  const channelInfo = {
    logo: data.subscribers[0]?.pic,
    title: data.shopName,
    shopId: data.shopId,
    data: data.subscribers,
    channel
  }
  return channelInfo
}
const getChannelInfo = (m, temp) => {
  channelInfo.value = WKSDK.shared().channelManager.getChannelInfo(to.value)// 获取频道详情(不会触发数据源的远程获取)
  let info = channelInfo.value?.data.find((item) => m.fromUID === item.uid)
  if (!info) {
    info = channelInfo.value?.data[0] // 客服被删除使用超管的信息
  }
  if (info) {
    return info[temp]
  }
}
// 监听cmd消息
let shopStatus = false
const isDestroyArr = []
const cmdListener = async (msg) => {
  if (msg.content.contentObj.cmd === 'userDestroy') {
    isDestroyArr.push(msg.content.contentObj.param)
  }
  if (isJSON(msg.content.contentObj.content)) {
    msg.content.contentObj.content = JSON.parse(msg.content.contentObj.content)
    if (msg.content.contentObj.content.type === -2) {
      maxReadSeq.value = msg.content.contentObj.content.content// 已读的最大序列号
    }
  }
  if (msg.content.contentObj?.cmd === 'shopStatus') {
    shopStatus = true
  }
}
</script>

<style lang="scss" scoped>
@use "./chat.scss";
</style>
